package com.humanminoritygame.model;

import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
import org.joda.time.Period;

@Entity
@Table(uniqueConstraints={@UniqueConstraint(columnNames={"roomId", "startDate"})})
public class Round extends PersistentEntity implements Comparable<Round> {

	@Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")
	private DateTime startDate;
	
	@Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")
	private DateTime dueDate;
	
	@Embedded
	private ResultSummary summary = null;
	
	@ManyToOne
	@JoinColumn(name="roomId")
	private Room room;

	Round() {
	}
	
	public Round(Room room) {
		super();
		this.room = room;
		this.startDate = new DateTime();
		this.dueDate = new DateTime(startDate).plus(Period.seconds(room.getCategory().getFrequency()));
	}

	@Override
	public int compareTo(Round o) {
		if (this.equals(o)) {
			return 0;
		}
		int cmp =startDate.compareTo(o.getStartDate());
		if(cmp == 0){
		  cmp =  room.compareTo(o.getRoom());
		}
		return cmp;
	}

	public DateTime getStartDate() {
		return startDate;
	}

	public boolean hasElapsed() {
	  return ! this.dueDate.isAfterNow();
	}

	
	@Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (!(obj instanceof Round))
      return false;
    final Round other = (Round) obj;
    if (getId() == null) {
      if (other.getId() != null)
        return false;
    } else if (!getId().equals(other.getId())){
      return false;
    }else if(!getStartDate().equals(other.getStartDate())){
      return false;
    }else if(!getRoom().equals(getRoom())){
      return false;
    }
    return true;
  }

  public Room getRoom() {
		return room;
	}

	public DateTime getDueDate() {
		return dueDate;
	}

	public ResultSummary getSummary() {
		return summary;
	}

	public void setSummary(ResultSummary summary) {
		this.summary = summary;
	}
	
	
	/**
	 * 
	 * @return the remaing time, expressed in miliseconds
	 */
  public int getRemainingTime() {
    return (int)( dueDate.getMillis() - (new DateTime().getMillis()) );
  }

}
